package com.zklh.leetcode.top100.problem207;

import java.util.*;

/**
 * 课程表算法实现
 *
 * @version 1.0
 * @Author tongnan
 * @Date 2023/10/27
 */
public class Solution1 {
    private Set<Integer> learnableCourse = new HashSet<>();

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        Map<Integer, Set<Integer>> prerequisiteMap = new HashMap<>();
        for (int[] prerequisite : prerequisites) {
            Set<Integer> courses = prerequisiteMap.getOrDefault(prerequisite[0], new HashSet<>());
            courses.add(prerequisite[1]);
            prerequisiteMap.put(prerequisite[0], courses);
        }
        for (int i = 0; i < numCourses; i++) {
            if (!dfs(new HashSet<>(), i, prerequisiteMap)) return false;
        }
        return true;
    }

    private boolean dfs(Set<Integer> courseTrace, int course, Map<Integer, Set<Integer>> prerequisiteMap) {
        if (learnableCourse.contains(course)) {
            return true;
        }
        if (courseTrace.contains(course)) {
            return false;
        }

        if (!prerequisiteMap.containsKey(course)) {
            learnableCourse.add(course);
            return true;
        }
        courseTrace.add(course);
        Set<Integer> directPrerequisiteCourses = prerequisiteMap.get(course);
        for (Integer directPrerequisiteCourse : directPrerequisiteCourses) {
            if (!dfs(courseTrace, directPrerequisiteCourse, prerequisiteMap)) {
                return false;
            }
        }
        courseTrace.remove(course);
        learnableCourse.add(course);
        return true;
    }


    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
/*        int numCourses = 2;
        int[][] prerequisites = {{1,0}};*/

/*        int numCourses = 4;
        int[][] prerequisites = {{0,1},{3,1},{1,3},{3,2}};*/

        int numCourses = 4;
        int[][] prerequisites = {{1,0},{2,6},{1,7},{6,4},{7,0},{0,5}};
        System.out.println(solution1.canFinish(numCourses, prerequisites));
    }
}